# coding:utf-8
# 技能管理

import traceback, uuid
from ujson import dumps, loads
from sqlalchemy import and_, or_
import glog, gdb
from db_tables import *


# { role_id : { skill:level, .. }, .. }
data = {}

def init ():
    pass


# 升级技能等级
def skill_level_up(role_id, skill):
    #* 检测技能类型,最大值判断
    #* 消耗物品

    if skill < 0: return False, '参数出错'

    data = get(role_id)
    if data is None: data = {}

    cur_lv = data.get(skill, 0)
    cur_lv += 1

    data[skill] = cur_lv
    return set(role_id, data)

# --------------------------------------------------
# 取得数据
def get (id):
    if not id in data:
        d = load_data_by_id(id)
        if d:
            data[id] = d
        else:
            return None
    try:
        d = data[id]
        return d
    except Exception, e:
        glog.error("skill_mgr>get, can not get this id:%s" % id)
        raise e


# 存储数据
def set (id, dt):
    buff = dumps(dt)

    if db_add_update(id, buff):
        data[id] = dt
        return True
    return False


# 从数据库中加载数据 数据是以json格式的字符串存储的
def load_data_by_id (id):
    dbdata = db_get(id)

    if dbdata is None:
        glog.log("skill_mgr>load_datas_by_id, db get None id:%s" % id)
        return None

    # 转成数据
    d = loads(dbdata.data)
    # d的key在存储的时候会变成字符串形式,转回来
    res = {}
    for k,v in d.iteritems():
        res[int(k)] = v
    return res


# ------------------------------------------------------
def db_add_update (id, data):
    ses = gdb.get_session()

    d = ses.query(DBSkill).filter_by(id=id).first()
    if d is None:
        # 创建
        d = DBSkill(id, data)
        try:
            ses.add(d)
            ses.commit()
            return True
        except Exception, e:
            ses.rollback()
            glog.log("skill_mgr>db_add_update, add data FAILED:%s" % id)
            return False
    else:
        # 更改
        d.data = data
        ses.commit()
        return True


def db_delete (id):
    ses = gdb.get_session()

    d = db_get(id)
    if d is None:
        glog.error("skill_mgr>db_delete FAILED (no this id:%s)" % id)
        return False

    ses.delete(dbrole)
    ses.commit()
    return True


def db_get (id):
    ses = gdb.get_session()
    return ses.query(DBSkill).filter_by(id=id).first()


